<template>
    <view class="index-page">
        <!-- 自定义导航栏 -->
        <CustomNavbar />
        <scroll-view
            :scroll-y="true"
            class="scroll-view"
            @scrolltolower="onScrollToLower"
            :refresher-enabled="true"
            :refresher-triggered="isRefreshing"
            @refresherrefresh="onRefresherRefresh"
        >
            <PageSkeleton v-if="isLoading" />
            <template v-else>
                <!-- 轮播图 -->
                <XtxSwiper :list="bannerList" />
                <!-- 前台分类 -->
                <CategoryPanel :list="categoryList" />
                <!-- 热门推荐 -->
                <HotPanel :list="hotList" />
                <XtxGuess ref="guessRef" />
            </template>
        </scroll-view>
    </view>
</template>

<script setup lang="ts">
//
import CustomNavbar from '@/pages/index/components/CustomNavbar.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home.ts'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import XtxSwiper from '@/components/XtxSwiper.vue'
import CategoryPanel from '@/pages/index/components/CategoryPanel.vue'
import HotPanel from '@/pages/index/components/HotPanel.vue'
import XtxGuess from '@/components/XtxGuess.vue'
import PageSkeleton from '@/pages/index/components/PageSkeleton.vue'
import { useGuessList } from '@/composables'

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
    const res = await getHomeBannerAPI()
    bannerList.value = res.result
}
// 获取前台分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
    const res = await getHomeCategoryAPI()
    categoryList.value = res.result
}

// 首页-热门推荐-小程序
const hotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
    const res = await getHomeHotAPI()
    hotList.value = res.result
}
// 触底加载更多数据
const { guessRef, onScrollToLower } = useGuessList()

// 下拉刷新
const isRefreshing = ref(false)
const onRefresherRefresh = async () => {
    // 下拉刷新时,开始动画
    isRefreshing.value = true
    guessRef.value?.resetData() // 重置猜您喜欢数据
    await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
    guessRef.value?.getMore() // 刷新猜您喜欢
    // 关闭动画
    isRefreshing.value = false
}
const isLoading = ref(false)
onLoad(async () => {
    isLoading.value = true
    await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
    isLoading.value = false
})
</script>
<style lang="scss">
/* #ifdef APP-PLUS */
#app,
/* #endif */
//
page {
    background-color: #f7f7f7;
    height: 100%;

    .index-page {
        height: 100%;
        display: flex;
        flex-direction: column;

        .scroll-view {
            flex: 1;
            overflow: hidden;
        }
    }
}
</style>
